package cn.jinbyte.starter.captcha.autoconfigure;

import cn.jinbyte.starter.captcha.config.EasyCaptchaProperties;
import cn.jinbyte.starter.captcha.service.CaptchaStore;
import cn.jinbyte.starter.captcha.service.DefaultCaptchaStore;
import cn.jinbyte.starter.captcha.service.EasyCaptchaService;
import cn.jinbyte.starter.captcha.service.ImgCaptchaService;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;

import static cn.jinbyte.starter.captcha.config.StarterConst.CONF_PREFIX;

/**
 * 验证码自动配置
 */
@Slf4j
@Data
@AutoConfiguration
@EnableConfigurationProperties(EasyCaptchaProperties.class)
@ConfigurationProperties(prefix = CONF_PREFIX)
@ConditionalOnProperty(prefix = CONF_PREFIX, name = "enabled", havingValue = "true")
public class CaptchaAutoConfiguration {

    /**
     * 是否启用验证码服务
     */
    private boolean enabled = false;

    /**
     * 验证码服务类型
     */
    private String provider = "EASY_CAPTCHA";

    @Bean
    @ConditionalOnMissingBean
    public CaptchaStore captchaStore() {
        return new DefaultCaptchaStore();
    }

    @Bean
    @ConditionalOnBean(CaptchaStore.class)
    @ConditionalOnProperty(prefix = CONF_PREFIX, name = "provider", havingValue = "EASY_CAPTCHA")
    public ImgCaptchaService captchaService(EasyCaptchaProperties properties, CaptchaStore captchaStore) {
        log.info("启用EasyCaptcha服务");
        return new EasyCaptchaService(properties, captchaStore);
    }
}
